package com.lottery.system.controller;
import com.lottery.system.common.errorcode.ControllerErrorCodeConstants;
import com.lottery.system.common.exception.ControllerException;
import com.lottery.system.common.pojo.CommonResult;
import com.lottery.system.common.utils.JacksonUtil;
import com.lottery.system.controller.param.UserLoginByCaptchaParam;
import com.lottery.system.controller.param.UserLoginByPasswordParam;
import com.lottery.system.controller.param.UserRegisterParam;
import com.lottery.system.controller.result.UserBaseInfoResult;
import com.lottery.system.controller.result.UserLoginResult;
import com.lottery.system.controller.result.UserRegisterResult;
import com.lottery.system.service.UserService;
import com.lottery.system.service.VerificationCodeService;
import com.lottery.system.service.dto.UserDTO;
import com.lottery.system.service.dto.UserLoginDTO;
import com.lottery.system.service.dto.UserRegisterDto;
import com.lottery.system.service.enums.IdentifyEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;

/**
 * @author: xiaoxie
 * create: 2024-09-02 21:11
 * @BelongsProject: lottery-system
 * @BelongsPackage: com.lottery.system.controller
 * description: 用户注册的控制层
 */
@RestController
@RequestMapping("/user")
public class UserController implements Serializable {
    @Autowired
    private UserService userService;
    @Autowired
    private VerificationCodeService verificationCodeService;

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * @description: 用户注册
     * @author: xiaoxie
     * @date: 2024/9/6 11:43
     * @param: [param]
     * @return: com.lottery.system.common.pojo.CommonResult<com.lottery.system.controller.result.UserRegisterResult>
     **/
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> register(
            @RequestBody @Validated UserRegisterParam param) {
        //打印日志
        logger.info("register param:{}", JacksonUtil.writeValueAsString(param));
        UserRegisterDto userRegisterDto = userService.register(param);
        return CommonResult.success(
                convertToUserRegisterResult(userRegisterDto));
    }
    /**
     * @description: 将业务逻辑层的返回结果转换成统一返回结果
     * @author: xiaoxie
     * @date: 2024/9/2 21:46
     * @param: [userRegisterDto]
     * @return: com.lottery.system.controller.result.UserRegisterResult
     **/
    private UserRegisterResult convertToUserRegisterResult(UserRegisterDto userRegisterDto) {
        if(null == userRegisterDto) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        UserRegisterResult userRegisterResult = new UserRegisterResult();
        userRegisterResult.setUserid(userRegisterDto.getUserId());
        return userRegisterResult;
    }

    /**
     * @description: 发送验证码
     * @author: xiaoxie
     * @date: 2024/9/4 12:01
     * @param: [phoneNumber]
     * @return: com.lottery.system.common.pojo.CommonResult<java.lang.Boolean>
     **/
    @GetMapping("/captcha/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber) {
        logger.info("sendVerification phoneNumber:{}", phoneNumber);
        if(null == phoneNumber) {
            logger.error(ControllerErrorCodeConstants.CAPTCHA_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.CAPTCHA_ERROR);
        }
        verificationCodeService.setVerificationCode(phoneNumber);
        return CommonResult.success(Boolean.TRUE);
    }
    /**
     * @description: 通过密码登录
     * @author: xiaoxie
     * @date: 2024/9/6 11:14
     * @param: [param]
     * @return: com.lottery.system.common.pojo.CommonResult<com.lottery.system.controller.result.UserLoginResult>
     **/
    @PostMapping("/password/login")
    public CommonResult<UserLoginResult> userLoginByPassword(
           @Validated @RequestBody UserLoginByPasswordParam param) {
        logger.info("userLoginByPassword param:{}", JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(
                convertToUserLoginResult(userLoginDTO));
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if(null == userLoginDTO) {
            logger.error(ControllerErrorCodeConstants.USER_LOGIN_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.USER_LOGIN_ERROR);
        }
        UserLoginResult userLoginResult = new UserLoginResult();
        userLoginResult.setToken(userLoginDTO.getToken());
        userLoginResult.setIdentify(userLoginDTO.getIdentify().name());
        return userLoginResult;
    }


    /**
     * @description: 通过手机验证码登录
     * @author: xiaoxie
     * @date: 2024/9/6 11:14
     * @param: [param]
     * @return: com.lottery.system.common.pojo.CommonResult<com.lottery.system.controller.result.UserLoginResult>
     **/
    @PostMapping("/captcha/login")
    public CommonResult<UserLoginResult> userLoginByCaptcha(
            @Validated @RequestBody UserLoginByCaptchaParam param) {
        logger.info("UserLoginByCaptchaParam param:{}", JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(
                convertToUserLoginResult(userLoginDTO));
    }
    /**
     * @description: 获取人员列表
     * @author: xiaoxie
     * @date: 2024/9/6 11:15
     * @param: [identity]
     * @return: com.lottery.system.common.pojo.CommonResult<java.util.List<com.lottery.system.controller.result.UserBaseInfoResult>>
     **/
    @RequestMapping("/getList")
    public CommonResult<List<UserBaseInfoResult>> getListUserInfo(String identity) {
        logger.info("getListUserInfo identity:{}", identity);
        List<UserDTO> userDTOList = userService.getListByIdentify(IdentifyEnum.forName(identity));
        return CommonResult.success(
                convertToUserList(userDTOList));
    }

    private List<UserBaseInfoResult> convertToUserList(List<UserDTO> userDTOList) {
       return userDTOList.stream()
                .map(userDTO -> {
                    UserBaseInfoResult userBaseInfoResult = new UserBaseInfoResult();
                    userBaseInfoResult.setUserId(userDTO.getUserId());
                    userBaseInfoResult.setUserName(userDTO.getUserName());
                    if (userDTO.getIdentify() == IdentifyEnum.ADMIN) {
                        userBaseInfoResult.setIdentify("管理员");
                    } else {
                        userBaseInfoResult.setIdentify("普通用户");
                    }
                    return userBaseInfoResult;
                }).toList();
    }

}
